'use strict';

const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';
let config = require(__dirname + '/../config/db.json')[env];
const association = require('./association')
var { snakecase, camelcase, capitalcase,spinalcase } = require('stringcase')
const db = {};

Object.assign(config, {
  define: {
    timestamps: true,
    freezeTableName: true,
    charset: 'utf8',
    dialectOptions: {
      collate: 'utf8mb4_general_ci'
    },
  },
  pool: {
    max: 10,
    idle: 30000,
    acquire: 60000,
  },
})

if(config.logging){
  config.logging = function(str){
    console.log(str);
  }
}


let sequelize = new Sequelize(config.database, config.username, config.password, config);

fs
  .readdirSync(__dirname)
  .filter(file => {
    return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js' && file!='association.js');
  })
  .forEach(file => {
    const model = require(path.join(__dirname, file))(sequelize, Sequelize.DataTypes);
    let modelName = camelcase(model.name)
    modelName = capitalcase(modelName)
    db[modelName] = model
  });

Object.keys(db).forEach(modelName => {
  if (db[modelName].associate) {
    db[modelName].associate(db);
  }
});


db.sequelize = sequelize;
db.Sequelize = Sequelize;

sequelize.doConnect = async function (){
  try {
    await sequelize.authenticate();
    association(db)
    console.log('数据库连接成功');
  } catch (error) {
    console.error('数据库连接失败:', error);
  }
}


module.exports = db;
